package io.traveller.apiGateway.server.filter.pre;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.traveller.apiGateway.client.route.RouteURLExt;
import io.traveller.apiGateway.server.context.RequestContextHelper;
import io.traveller.apiGateway.client.discovery.DiscoveryClientRouteExtLocator;
import io.traveller.apiGateway.server.filter.FilterType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UrlPathHelper;

/**
 * 获取RouteExt信息Filter
 * 依赖{@link org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter}解析的serviceId
 *
 * Created by yunai on 16/9/6.
 */
public class PreGetRouteExtFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(PreGetRouteExtFilter.class);

    private DiscoveryClientRouteExtLocator routeExtLocator;

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    public PreGetRouteExtFilter(DiscoveryClientRouteExtLocator routeExtLocator) {
        this.routeExtLocator = routeExtLocator;
    }

    @Override
    public String filterType() {
        return FilterType.PRE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        // 静态资源不路由

        // 依赖PreDecorationFilter解析的serviceId
        RequestContext ctx = RequestContext.getCurrentContext();
        final String serviceId = RequestContextHelper.getServiceId(ctx);
        return StringUtils.hasText(serviceId);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // 做必要性数据校验
        final String serviceId = RequestContextHelper.getServiceId(ctx);
        Assert.isTrue(StringUtils.hasText(serviceId), "serviceId 必须存在.");
        // 获取RouteExt信息
        final String requestURI = RequestContextHelper.getRequestURI(ctx);
        final String requestMethod = RequestContextHelper.getRequestMethod(ctx);
        RouteURLExt routeURLExt = routeExtLocator.getMatchingRouteURLExt(serviceId, requestURI, requestMethod);
        if (routeURLExt == null) {
            logger.debug("[run][routeURLExt({}/{}) 无法找到.]", serviceId, requestURI);
            return null;
        }
        Assert.notNull(routeURLExt.getRouteExt(), "routeURLRoute.routeExt 不能为空.");
        Assert.notNull(routeURLExt.getSecurityLevel(), "routeURLRoute.securityLevel 不能为空.");
        RequestContextHelper.setServiceSys(ctx, routeURLExt.getRouteExt().getServiceSys());
        RequestContextHelper.setAccountSys(ctx, routeURLExt.getRouteExt().getAccountSys());
        RequestContextHelper.setAutoGenVisitor(ctx, routeURLExt.getRouteExt().isAutoGenVisitor());
        RequestContextHelper.setSecurityLevel(ctx, routeURLExt.getSecurityLevel());
        return routeURLExt;
    }

}